﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using OpenGL;

namespace Exhibition
{
	public class Wall
	{
		public int ID;
		public V3D P1, P2;
		public double Length
		{
			get
			{
				return (P2 - P1).Length;
			}
		}
		public GLTexture T;

		public double Width, Height;

		public Wall(int id,V3D p1, V3D p2, double w, double h, GLTexture txt)
		{
			ID = id;
			P1 = p1;
			P2 = p2;
			Width = w;
			Height = h;
			T = txt;
		}
		public Wall(int id,double x1, double y1, double z1, double x2, double y2, double z2, double w, double h, GLTexture txt)
		{
			ID = id;
			P1 = new V3D(x1, y1, z1);
			P2 = new V3D(x2, y2, z2);
			Width = w;
			Height = h;
			T = txt;
		}
		void DrawQuad(V3D p1, V3D p2, double h, int tile)
		{
			const double Tile = 1;
			for (int i = 0; i < Tile; i++)
				for (int j = 0; j < Tile; j++)
				{
					double H = h / Tile;
					V3D P1 = new V3D((i + 0.5) / Tile * (p2 - p1).Length, (j + 0.5) / Tile * h, 0);

					GL.glPushMatrix();
					GL.glTranslated(p1.X, p1.Y, p1.Z);
					GL.glRotated(V3D.AbsAngleD(V3D.Red, (p2 - p1).Unit, V3D.Green), 0, 1, 0);
					GL.glTranslated(P1.X, P1.Y, 0);
					T.Draw((p2 - p1).Length / Tile, h / Tile, 1, tile);
					GL.glPopMatrix();
				}
		}
		public void Draw()
		{
			//GL.glBegin(GL.GL_QUADS);
			V3D W = ((P2 - P1) % V3D.Green).Unit * (Width / 2);
			DrawQuad(P1 + W, P2 + W, Height, 4);
			DrawQuad(P2 - W, P1 - W, Height, 4);
			DrawQuad(P1 - W, P1 + W, Height, 1);
			DrawQuad(P2 + W, P2 - W, Height, 1);

			GL.glPushAttrib(GL.GL_ALL_ATTRIB_BITS);
			GL.glDisable(GL.GL_TEXTURE_2D);
			GL.glDisable(GL.GL_LIGHTING);
			GL.glDisable(GL.GL_BLEND);
			GL.glColor3d(0, 0, 0);
			GL.glBegin(GL.GL_QUADS);
			GL.glV3D(P1 + W + V3D.Green * Height);
			GL.glV3D(P1 - W + V3D.Green * Height);
			GL.glV3D(P2 - W + V3D.Green * Height);
			GL.glV3D(P2 + W + V3D.Green * Height);
			GL.glEnd();
			GL.glPopAttrib();
		}

		double Angle(bool backside)
		{
			return V3D.AbsAngleD(V3D.Red, (P2 - P1).Unit * (backside ? -1 : 1), V3D.Green);
		}
		public void GLTrans(bool backside, double wallx)//Transfers to center line at wallx
		{
			V3D p1 = backside ? P2 : P1;
			V3D p2 = backside ? P1 : P2;
			GL.glTranslated(p1.X, p1.Y + Height / 2, p1.Z);
			GL.glRotated(Angle(backside), 0, 1, 0);
			GL.glTranslated(wallx, 0, Width / 2 + 0.05);
		}
		public V3D GetPosition(bool backside, double wallx, double height)
		{
			V3D p1 = backside ? P2 : P1;
			V3D p2 = backside ? P1 : P2;
			V3D d = (p2 - p1).Unit;

			return p1 + d * wallx + V3D.Green * height + d.RotY(-90) * (Width / 2 + 0.05);
		}
		public V3D GetNormal(bool backside)
		{
			V3D p1 = backside ? P2 : P1;
			V3D p2 = backside ? P1 : P2;
			return (p2 - p1).Unit.RotY(-90);
		}
	}
}